<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <!-- 添加商品步骤显示器 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs区域 -->
      <!-- tab-position指定tabs展示的位置 -->
      <!-- v-model接受的是字符型的数据 -->
      <!-- label-position:'top'可以用来改变form的位置 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!-- before-leave是一个属性所以用v-bind进行绑定，但其返回值是一个函数 -->
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="leaveHandle"
          @tab-click="tabClickHandle"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- options只想数据源 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="addProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="(item,index) in manyData" :key="index">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" border v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <!-- 上传按钮 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
              :headers="headers"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_intorduces"></quill-editor>
            <el-button @click="addGoods" type="primary" class="editBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片的对话框 -->
    <el-dialog title="图片预览" :visible.sync="perviewDialog" width="50%">
      <img :src="previewPath" class="preveImg" />
    </el-dialog>
  </div>
</template>

<script>
// 导入lodash
import _ from 'lodash'
export default {
  name: 'AddGood',
  data() {
    return {
      previewPath: '', // 预览图片默认展示路劲
      perviewDialog: false, // 图片预览对话框的可见性
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 用来存储所有三级分类的参数
      onlyData: [],
      manyData: [],
      addProps: {
        label: 'cat_name',
        value: 'cat_id', // 绑定的值
        children: 'children',
        expandTrigger: 'hover'
      }, // 添加分类的props规则
      cateList: [], // 分类数据的数组
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品数量', trigger: 'blur' }]
      }, // 添加表单的验证规则
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 添加商品分类
        goods_cat: [],
        pics: [],
        attrs: []
      }, // 添加表单数据的对象
      activeIndex: '0',
      goods_intorduces: ''
    }
  },
  methods: {
    // 点击添加商品按钮触发的事件
    addGoods() {
      // 点击添加按钮先对表单数据进行验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.info('请先输入字段')
        }
        // 添加具体的逻辑，将其深拷贝（_.cloneDeep）一份goods_cat
        // cloneDeep(要克隆的方法)
        // 为什么需要克隆，不直接添加goods_cat到原来的数组当中：因为级联选择器双向绑定了数据cat
        // 如果我们将cat转化成数组，在基本信息当中获取表单数据会报错
        // 方法一、利用深拷贝
        const newAddForm = _.cloneDeep(this.addForm)
        newAddForm.goods_cat = newAddForm.goods_cat.join(',')

        // 方法二、利用展开运算符
        // const newAddForm = { ...this.addForm }
        // newAddForm.goods_cat = newAddForm.goods_cat.join(',')
        // 将动态参数进行遍历
        this.manyData.forEach(item => {
          const newParams = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
            // 因为动态参数的attr_vals返回值是一个数组，但我们要求结果是一个字符串
          }
          // 将新添加的对象推送到addFrom当中
          this.addForm.attrs.push(newParams)
        })
        // 将静态属性进行遍历获取他的每一项
        this.onlyData.forEach(item => {
          const newParams = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
            // 因为静态参数的返回值是一个字符串，所以我们不需要转换
          }
          this.addForm.attrs.push(newParams)
        })
        // 将克隆新的数组的参数attrs数组进行重新的赋值===原来数组的值
        newAddForm.attrs = this.addForm.attrs
        // 发起请求添加数据
        const { data: res } = await this.$http.post('/goods', newAddForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    },

    // 处理图片成功上传的操作
    // on-success中有一个参数就是response
    handleSuccess(response) {
      const picInfo = { pic: response.data.tmp_path }
      // 将获取到的图片的路径添加到addForm的pics数组中进行保存
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },

    // 点击预览图片的操作
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.perviewDialog = true
    },

    // 处理图片移除的操作
    // file指代的是要删除的图片的信息
    handleRemove(file) {
      const removeFile = file.response.tmp_path
      const index = this.addForm.pics.findIndex(item => {
        return item.pics === removeFile
      })
      // 移除对应的图片
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },

    // 当点击tab切换触发的时间，来获取数据
    async tabClickHandle() {
      if (this.activeIndex === '1') {
        // 说明成功跳转到参数详情页面，再点击的时候发送和请求
        const { data: res } = await this.$http.get(`categories/${this.isId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data
        // console.log(this.manyData)
      } else if (this.activeIndex === '2') {
        // 说明成功跳转到参数详情页面，再点击的时候发送和请求
        const { data: res } = await this.$http.get(`categories/${this.isId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        // res.data.forEach(item => {
        //   item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        // })
        this.onlyData = res.data
        // console.log(this.manyData)
      }
    },

    // 当tab栏切换触发的事件
    leaveHandle(activeName, oldActiveName) {
      // 注意其有特定的顺序问题，前者必须是要跳转到的页面，后者是从哪个页面开始跳转
      // 如果之前跳转的tab栏名称是0,且分类没有选择时我们就不让其跳转
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择分类')
        return false
      }
    },

    // 当级联选择器改变以后触发
    handleChange() {
      console.log(this.addForm.goods_cat)
      // 只允许选择三级分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },

    // 获取所有的分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // console.log(res)
      this.cateList = res.data
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    isId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-tabs {
  margin-top: 25px;
}
.preveImg {
  width: 100%;
}
/deep/ .el-form-item__label {
  width: 133px;
}
.el-form-item__content {
  margin-left: 140px;
}
/deep/.ql-container {
  min-height: 300px;
}
.editBtn {
  margin-top: 15px;
}
</style>
